<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>用户登录</h2>
        <p>请输入手机号和验证码进行登录</p>
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        label-width="0"
        class="login-form"
      >
        <!-- 手机号输入 -->
        <el-form-item prop="phone">
          <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            prefix-icon="Phone"
            clearable
            @input="handlePhoneInput"
          />
        </el-form-item>

        <!-- 图片验证码 -->
        <el-form-item prop="imageCode">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.imageCode"
              placeholder="请输入图片验证码"
              prefix-icon="Picture"
              clearable
              style="flex: 1; margin-right: 10px;"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img 
                v-if="captchaUrl" 
                :src="captchaUrl" 
                alt="验证码"
                style="width: 100%; height: 100%; cursor: pointer;"
              />
              <div v-else class="captcha-loading">
                <el-icon><Loading /></el-icon>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 发送短信按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="sendingSMS"
            :disabled="!canSendSMS"
            @click="sendSMS"
            style="width: 100%;"
          >
            {{ sendButtonText }}
          </el-button>
        </el-form-item>

        <!-- 短信验证码 -->
        <el-form-item prop="smsCode">
          <el-input
            v-model="loginForm.smsCode"
            placeholder="请输入短信验证码"
            prefix-icon="Message"
            clearable
            maxlength="4"
            show-word-limit
          />
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button 
            type="success" 
            :loading="loggingIn"
            :disabled="!canLogin"
            @click="handleLogin"
            style="width: 100%;"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 分割线 -->
      <div class="divider">
        <span>或</span>
      </div>

      <!-- 错误信息显示 -->
      <div v-if="errorMessage" class="error-message">
        <el-alert
          :title="errorMessage"
          type="error"
          :closable="false"
          show-icon
        />
      </div>

      <!-- 第三方登录提示 -->
      <div class="third-party-tip">
        <span>您可以通过以下第三方账号登录</span>
      </div>

      <!-- 第三方登录按钮 -->
      <div class="third-party-login">
        <div 
          class="third-party-item"
          :class="{ 'loading': qqLoggingIn }"
          @click="handleQQLogin"
        >
          <div class="third-party-icon qq-icon">
            <span>🐧</span>
          </div>
          <div class="third-party-name">QQ</div>
        </div>
        
        <div 
          class="third-party-item"
          :class="{ 'loading': wechatLoggingIn }"
          @click="handleWeChatLogin"
        >
          <div class="third-party-icon wechat-icon">
            <span>💬</span>
          </div>
          <div class="third-party-name">微信</div>
        </div>
        
        <div 
          class="third-party-item"
          :class="{ 'loading': giteeLoggingIn }"
          @click="handleGiteeLogin"
        >
          <div class="third-party-icon gitee-icon">
            <span>🐙</span>
          </div>
          <div class="third-party-name">Gitee</div>
        </div>
        
        <div 
          class="third-party-item"
          :class="{ 'loading': dingTalkLoggingIn }"
          @click="handleDingTalkLogin"
        >
          <div class="third-party-icon dingtalk-icon">
            <span>🔔</span>
          </div>
          <div class="third-party-name">钉钉</div>
        </div>
      </div>

      <!-- 倒计时显示 -->
      <div v-if="countdown > 0" class="countdown">
        <el-text type="info">{{ countdown }}秒后可重新发送</el-text>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Phone, Picture, Message, Loading } from '@element-plus/icons-vue'
import { authAPI } from '@/api/index'
import { v4 as uuidv4 } from 'uuid';



const router = useRouter()

// 表单引用
const loginFormRef = ref()

// 表单数据
const loginForm = reactive({
  phone: '',
  imageCode: '',
  smsCode: '',
  uuid: ''
})

// 表单验证规则
const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  imageCode: [
    { required: true, message: '请输入图片验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
  ]
}

// 状态变量
const captchaUrl = ref('')
const sendingSMS = ref(false)
const loggingIn = ref(false)
const qqLoggingIn = ref(false)
const wechatLoggingIn = ref(false)
const giteeLoggingIn = ref(false)
const dingTalkLoggingIn = ref(false)
const countdown = ref(0)
const countdownTimer = ref(null)
const errorMessage = ref('')

// 计算属性
const canSendSMS = computed(() => {
  return loginForm.phone && loginForm.imageCode && countdown.value === 0
})

const canLogin = computed(() => {
  return loginForm.phone && loginForm.smsCode
})

const sendButtonText = computed(() => {
  if (sendingSMS.value) return '发送中...'
  if (countdown.value > 0) return `${countdown.value}s后重发`
  return '发送短信验证码'
})

// 生成UUID
const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}


// 刷新图片验证码
const refreshCaptcha = () => {
  loginForm.uuid = generateUUID()
  console.log('生成新的UUID:', loginForm.uuid)
  
  // 构建验证码URL
  const baseUrl = 'http://localhost:8000/api/imagecode/'
  captchaUrl.value = `${baseUrl}?uuid=${loginForm.uuid}&t=${Date.now()}`
  
  console.log('验证码URL:', captchaUrl.value)
  
  // 添加错误处理
  const img = new Image()
  img.crossOrigin = 'anonymous' // 添加跨域支持
    
  img.onload = () => {
    console.log('验证码图片加载成功')
  }
  
  img.onerror = (error) => {
    console.error('验证码图片加载失败:', error)
    console.error('失败的URL:', captchaUrl.value)
    ElMessage.error('验证码图片加载失败，请重试')
    
    // 尝试重新加载
    setTimeout(() => {
      captchaUrl.value = `${baseUrl}?uuid=${loginForm.uuid}&t=${Date.now()}`
    }, 1000)
  }
  
  img.src = captchaUrl.value
}

// 手机号输入处理
const handlePhoneInput = () => {
  // 只允许输入数字
  loginForm.phone = loginForm.phone.replace(/\D/g, '')
  // 限制长度为11位
  if (loginForm.phone.length > 11) {
    loginForm.phone = loginForm.phone.slice(0, 11)
  }
}

// 发送短信验证码
const sendSMS = async () => {
  if (!canSendSMS.value) return

  try {
    sendingSMS.value = true
    
    const response = await authAPI.sendSMS({
      phone: loginForm.phone,
      code: loginForm.imageCode,
      uuid: loginForm.uuid
    })

    if (response.success) {
      ElMessage.success('短信验证码发送成功')
      startCountdown()
    } else {
      ElMessage.error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送短信失败:', error)
  } finally {
    sendingSMS.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer.value)
      countdownTimer.value = null
    }
  }, 1000)
}

// 登录处理
const handleLogin = async () => {
  if (!canLogin.value) return

  try {
    await loginFormRef.value.validate()
    
    loggingIn.value = true
    
    const response = await authAPI.login({
      phone: loginForm.phone,
      sms_code: loginForm.smsCode
    })

    if (response.success) {
      // 保存token、retoken和用户信息到localStorage
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('retoken', response.data.retoken)
      localStorage.setItem('userInfo', JSON.stringify({
        user_id: response.data.user_id,
        phone: response.data.phone,
        username: response.data.username
      }))

      ElMessage.success('登录成功')
      
      // 跳转到首页或其他页面
      router.push('/')
    } else {
      ElMessage.error(response.message || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    loggingIn.value = false
  }
}

// QQ登录处理
const handleQQLogin = async () => {
  try {
    qqLoggingIn.value = true
    
    // 获取QQ登录URL并跳转
    const response = await authAPI.qqLogin()
    if (response.code === 200 && response.data && response.data.url) {
      window.location.href = response.data.url
    } else {
      throw new Error(response.message || '获取QQ登录URL失败')
    }
    
  } catch (error) {
    console.error('QQ登录失败:', error)
    ElMessage.error('QQ登录失败，请重试')
    qqLoggingIn.value = false
  }
}

// 微信登录处理
const handleWeChatLogin = async () => {
  try {
    wechatLoggingIn.value = true
    
    // 获取微信登录URL并跳转
    const response = await authAPI.wechatLogin()
    if (response.code === 200 && response.data && response.data.url) {
      window.location.href = response.data.url
    } else {
      throw new Error(response.message || '获取微信登录URL失败')
    }
    
  } catch (error) {
    console.error('微信登录失败:', error)
    ElMessage.error('微信登录失败，请重试')
    wechatLoggingIn.value = false
  }
}

// Gitee登录处理
const handleGiteeLogin = async () => {
  try {
    giteeLoggingIn.value = true
    errorMessage.value = '' // 清除之前的错误信息
    
    // 获取Gitee登录URL并跳转
    const response = await authAPI.giteeLogin()
    console.log('Gitee登录响应:', response) // 添加调试日志
    
    if (response && response.code === 200 && response.data && response.data.url) {
      console.log('准备跳转到Gitee授权页面:', response.data.url)
      console.log('当前页面URL:', window.location.href)
      
      // 直接在当前页面跳转到Gitee授权页面
      try {
        console.log('开始执行跳转...')
        window.location.href = response.data.url
        console.log('跳转命令已执行')
      } catch (error) {
        console.error('跳转失败:', error)
        throw error
      }
    } else {
      const errorMsg = response?.message || '获取Gitee登录URL失败'
      errorMessage.value = errorMsg
      throw new Error(errorMsg)
    }
    
  } catch (error) {
    console.error('Gitee登录失败:', error)
    const errorMsg = error.message || 'Gitee登录失败，请重试'
    errorMessage.value = errorMsg
    ElMessage.error(errorMsg)
  } finally {
    giteeLoggingIn.value = false
  }
}

// 钉钉登录处理
const handleDingTalkLogin = async () => {
  try {
    dingTalkLoggingIn.value = true
    errorMessage.value = '' // 清除之前的错误信息
    
    // 获取钉钉登录URL并跳转
    const response = await authAPI.dingTalkLogin()
    console.log('钉钉登录响应:', response)
    
    if (response && response.code === 200 && response.data && response.data.url) {
      console.log('准备跳转到钉钉授权页面:', response.data.url)
      
      // 直接在当前页面跳转到钉钉授权页面
      try {
        console.log('开始执行跳转...')
        window.location.href = response.data.url
        console.log('跳转命令已执行')
      } catch (error) {
        console.error('跳转失败:', error)
        throw error
      }
    } else {
      const errorMsg = response?.message || '获取钉钉登录URL失败'
      errorMessage.value = errorMsg
      throw new Error(errorMsg)
    }
    
  } catch (error) {
    console.error('钉钉登录失败:', error)
    const errorMsg = error.message || '钉钉登录失败，请重试'
    errorMessage.value = errorMsg
    ElMessage.error(errorMsg)
  } finally {
    dingTalkLoggingIn.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  refreshCaptcha()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 8px;
  font-size: 24px;
}

.login-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.error-message {
  margin-bottom: 20px;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-image {
  width: 100px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.captcha-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #909399;
}

.countdown {
  text-align: center;
  margin-top: 10px;
}

.divider {
  text-align: center;
  margin: 20px 0;
  position: relative;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #dcdfe6;
}

.divider span {
  background: white;
  padding: 0 15px;
  color: #909399;
  font-size: 14px;
}

.third-party-tip {
  text-align: center;
  margin: 20px 0 15px 0;
  color: #666;
  font-size: 14px;
}

.third-party-login {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.third-party-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 10px;
  border-radius: 8px;
}

.third-party-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.third-party-item.loading {
  opacity: 0.6;
  cursor: not-allowed;
}

.third-party-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  font-size: 24px;
}

.third-party-icon.qq-icon {
  background: #12b7f5;
  color: white;
}

.third-party-icon.wechat-icon {
  background: #07C160;
  color: white;
}

.third-party-icon.gitee-icon {
  background: #c71d23;
  color: white;
}

.third-party-icon.dingtalk-icon {
  background: #1890ff;
  color: white;
}

.third-party-name {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-box {
    padding: 20px;
  }
  
  .captcha-image {
    width: 80px;
  }
}
</style>
